<template>
	<view class="container">
		<!-- 自定义导航栏 -->
		<!-- position: fixed; -->
		<view
			style="display: flex; align-items: center; width: 100%; box-sizing: border-box;  top: 0; left: 0; background-color: #fff; z-index: 99"
			:style="{ height: navheight + 'px', 'padding-top': hometop + 'px' }">
			<view style="width: 100%; text-align: center">
				<text style="font-weight: 500; font-size: 32rpx; color: #151515">消息</text>
			</view>
		</view>
		<!-- 站位盒子 -->
		<view :style="{ height: navheight + 'px', width: '100%' }"></view>
		<!-- 消息列表 -->
		<view class="shenhe" @tap="joop">
			<image src="../../static/messageimg/groupshenhe.png" style="width: 100rpx; height: 100rpx" mode=""></image>
			<view style="margin-left: 24rpx">
				<view style="font-weight: 500; font-size: 32rpx; color: #151515">入群审核</view>
				<view
					style="font-weight: 400; font-size: 28rpx; color: #666666; margin-top: 12rpx; white-space: nowrap; width: 500rpx; overflow: hidden; text-overflow: ellipsis"
					v-if="chatlist[0]">
					{{ chatlist[0].user.nickname }}申请加入{{ chatlist[0].group.group_name }}
				</view>
			</view>
		</view>
		<view class="msglist" v-for="(i, k) in list" :key="k">
			<!-- 单聊消息 -->
			<view class="item" v-if="i.conversationType == 1"
				@tap="util.urlTo('/dynamic/sixin/sixin?id=' + i.targetId)">
				<!-- <image
          :src="
            i.latestMessage.senderUserId == userid ? img_url + JSON.parse(i.latestMessage.content.extra).receiveHead : img_url + JSON.parse(i.latestMessage.content.extra).sendHead
          "
          style="width: 100rpx; height: 100rpx"
          mode="aspectFill"
        ></image> -->
				<image :src="img_url + i.avatar" style="width: 100rpx; height: 100rpx" mode="aspectFill"></image>
				<view style="max-width: 570rpx; margin-left: 24rpx">
					<!-- 用户信息 -->
					<view style="display: flex; justify-content: space-between; align-items: center">
						<view>
							<text style="font-weight: 500; font-size: 32rpx; color: #151515">
								{{ i.latestMessage.senderUserId == userid ? JSON.parse(i.latestMessage.content.extra).receiveName : JSON.parse(i.latestMessage.content.extra).sendName }}
							</text>
							<!-- <image
                :src="JSON.parse(i.latestMessage.content.extra).allnum == 1 ? '../../static/myimg/a9.png' : ' ../../static/myimg/a8.png'"
                style="width: 28rpx; height: 28rpx; vertical-align: middle; margin-left: 12rpx"
                mode=""
              ></image> -->
							<image :src="i.gender == 1 ? '../../static/myimg/a8.png' : ' ../../static/myimg/a9.png'"
								style="width: 28rpx; height: 28rpx; vertical-align: middle; margin-left: 12rpx" mode="">
							</image>
						</view>
						<!-- <view>{{timeChange(i.latestMessage.sentTime)}}</view> -->
					</view>
					<!-- 消息 -->
					<view style="display: flex; align-items: center; justify-content: space-between">
						<view
							style="overflow: hidden; width: 520rpx; white-space: nowrap; text-overflow: ellipsis; font-weight: 400; font-size: 28rpx; color: #666666; max-width: 520rpx">
							{{
                i.latestMessage.messageType == 'RC:ImgMsg'
                  ? '[图片]'
                  : i.latestMessage.messageType == 'RC:TxtMsg'
                  ? i.latestMessage.content.content
                    ? i.latestMessage.content.content
                    : '申请交换微信中'
                  : '[语音消息]'
              }}
						</view>
						<view style="
                width: 30rpx;
                height: 30rpx;
                border-radius: 50%;
                text-align: center;
                line-height: 30rpx;
                background-color: red;
                color: #fff;
                font-weight: 400;
                font-size: 20rpx;
                color: #ffffff;
              " v-if="i.unreadMessageCount != 0">
							{{ i.unreadMessageCount }}
						</view>
					</view>
				</view>
			</view>
			<!-- 群聊消息 -->
			<view class="item" v-if="i.conversationType == 3"
				@tap="util.urlTo('/message/groupmsg/groupmsg?id=' + i.targetId)">
				<view class="" style="display: flex; align-items: center">
					<view style="width: 100rpx; height: 100rpx; border-radius: 12rpx 12rpx 12rpx 12rpx">
						<image :src="img_url + JSON.parse(i.latestMessage.content.extra).receiveHead"
							style="width: 100rpx; height: 100rpx; border-radius: 12rpx 12rpx 12rpx 12rpx"
							mode="aspectFill"></image>
					</view>
					<view style="max-width: 570rpx; margin-left: 24rpx">
						<!-- 用户信息 -->
						<view style="display: flex; justify-content: space-between; align-items: center">
							<view>
								<text style="font-weight: 500; font-size: 32rpx; color: #151515">
									{{ JSON.parse(i.latestMessage.content.extra).receiveName }}({{ JSON.parse(i.latestMessage.content.extra).allnum }})
								</text>
							</view>
							<!-- 消息时间 -->
							<view></view>
						</view>
						<!-- 消息 -->
						<view style="display: flex; align-items: center; justify-content: space-between">
							<view
								style="overflow: hidden; max-width: 520rpx; width: 520rpx; white-space: nowrap; text-overflow: ellipsis; font-weight: 400; font-size: 28rpx; color: #666666">
								{{
                  i.latestMessage.messageType == 'RC:TxtMsg'
                    ? JSON.parse(i.latestMessage.content.extra).sendName + ':' + i.latestMessage.content.content
                    : i.latestMessage.messageType == 'RC:ImgMsg'
                    ? JSON.parse(i.latestMessage.content.extra).sendName + ':' + '[图片]'
                    : JSON.parse(i.latestMessage.content.extra).sendName + ':' + '[语音消息]'
                }}
							</view>
						</view>
					</view>
					<view style="
              width: 30rpx;
              height: 30rpx;
              border-radius: 50%;
              text-align: center;
              line-height: 30rpx;
              background-color: red;
              color: #fff;
              font-weight: 400;
              font-size: 20rpx;
              color: #ffffff;
            " v-if="i.unreadMessageCount != 0">
						{{ i.unreadMessageCount }}
					</view>
				</view>
			</view>
		</view>
		<!-- 新增内容 4：私信界面背景提示文字 -->
		<view v-if="!isShow"
			style="width: 100%; text-align: center; font-size: 40rpx; font-weight: blod; margin-top: 500rpx">
			您还没有登录，登录后就可以聊天啦</view>
		<!--站位盒子 -->
		<view style="height: 156rpx"></view>
		<!-- d底部组件 -->
		<TabBar @choosetab="choosetab" :unreadmsg="unreadmsg" :tabbarindex="tabbarindex"></TabBar>
		<push v-if="showpush" @closeshowpush="closepush" @gopush="gopush"></push>
	</view>
</template>

<script>
	const RongIMLib = require('@rongcloud/imlib-next');
	import push from '@/components/pushact.vue';
	import TabBar from '@/components/tabbar.vue';
	export default {
		components: {
			TabBar,
			push
		},
		data() {
			return {
				isShow: false, // 未登录展示提示
				unreadmsg: 0, // 未读消息的总数
				timer: null,
				tabbarindex: 3,
				showpush: false,
				hometop: '',
				navheight: '',
				list: [],
				img_url: this.img_url,
				chatlist: [],
				userid: uni.getStorageSync('user').id
			};
		},
		async onShow() {
			this.isShow = !!uni.getStorageSync('token');
			console.log('是否显示', this.isShow);
			this.list.length = 0;
			this.unreadmsg = 0;
			await this.getConversationList();
			if (uni.getStorageSync('token')) {
				this.getApplyGroupLog();
			}
			const Events = RongIMLib.Events;
			RongIMLib.addEventListener(Events.MESSAGES, (evt) => {
				console.log(evt.messages);
				// this.utilim.addEventListener().then((res) => {
				//   console.log('监听器', res);
				//   console.log(1111111111);

				// });
				this.IM.getConversationList({
					count: 10
				}).then((res) => {
					if (res.code === 0) {
						console.log('群聊变化');
						console.log(res.code, '起初回话列表', res.data);
						// 在此处传递未读消息的数量
						this.unreadmsg = 0;
						res.data.forEach((item) => {
							this.unreadmsg += item.unreadMessageCount;
						});
						res.data.forEach(async (item, index) => {
							if (item.conversationType == 1) {
								await this.http('/user/infor', {
									user_id: item.targetId
								}).then((res2) => {
									// console.log('单聊人员信息', res2);
									item.name = res2.data.nickname;
									item.avatar = res2.data.avatar;
									item.gender = res2.data.gender;
								});
							}
							if (item.unreadMessageCount != 0) {
								this.list.forEach((item2) => {
									if (item.targetId == item2.targetId) {
										item2.unreadMessageCount = item
											.unreadMessageCount;
										item2.latestMessage.content = item
											.latestMessage.content;
									}
								});
							}
						});

						console.log('追加后的数据', this.list);
					} else {
						console.log(res.code, res.msg);
					}
				});
			});

			// this.timer = setInterval(() => {

			// }, 1000);
		},
		onReachBottom() {
			console.log('触底了');
			this.IM.getConversationList({
				count: 10,
				order: 0,
				startTime: this.list[this.list.length - 1].latestMessage.sentTime
			}).then(async (res) => {
				if (res.code === 0 && res.data.length != 0) {
					console.log('群聊变化');
					console.log(res.code, '回话列表', res.data);
					// 在此处传递未读消息的数量
					this.unreadmsg = 0;
					await res.data.forEach(async (item) => {
						if (item.conversationType == 1) {
							await this.http('/user/infor', {
								user_id: item.targetId
							}).then((res2) => {
								console.log('单聊人员信息', res2);
								item.name = res2.data.nickname;
								item.avatar = res2.data.avatar;
								item.gender = res2.data.gender;
							});
						}
						this.unreadmsg += item.unreadMessageCount;
					});
					this.$nextTick(() => {
						setTimeout(() => {
							this.list.push(...res.data);
						}, 500);
					});

					console.log('追加后的数据', this.list);
				} else {
					console.log(res.code, res.msg);
				}
			});
		},
		onLoad() {
			const app = getApp();
			this.hometop = app.globalData.capsule.top; // 胶囊到顶部的距离
			this.navheight = (app.globalData.capsule.top - app.globalData.system.statusBarHeight) * 2 + app.globalData
				.capsule.height + app.globalData.system.statusBarHeight; // 头部盒子的高度
		},

		methods: {
			getApplyGroupLog() {
				this.http('/group/getApplyGroupLog', {}).then((res) => {
					this.chatlist = res.data;
				});
			},
			timeChange(timestamp) {
				var date = new Date(timestamp * 1000); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
				var Y = date.getFullYear() + '-';
				var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
				var D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' ';
				var h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
				var m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':';
				var s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();
				return Y + M + D + h + m + s;
			},

			// 获取回话列表
			getConversationList() {
				this.IM.getConversationList({
					count: 10
				}).then(async (res) => {
					if (res.code === 0) {
						console.log('群聊变化');
						console.log(res.code, '起初回话列表', res.data);
						// 在此处传递未读消息的数量
						this.unreadmsg = 0;
						await res.data.forEach(async (item) => {
							if (item.conversationType == 1) {
								await this.http('/user/infor', {
									user_id: item.targetId
								}).then((res2) => {
									console.log('单聊人员信息', res2);
									item.name = res2.data.nickname;
									item.avatar = res2.data.avatar;
									item.gender = res2.data.gender;
								});
							}
							this.unreadmsg += item.unreadMessageCount;
						});
						this.$nextTick(() => {
							setTimeout(() => {
								this.list = res.data;
							}, 500);
						});

						console.log('追加后的数据', this.list);
					} else {
						console.log(res.code, res.msg);
					}
				});
			},
			joop() {
				uni.navigateTo({
					url: '/message/groupapply/groupapply'
				});
			},
			//发布动态
			gopush(index) {
				if (index == 1) {
					this.showpush = false;
					// 发布活动
					uni.navigateTo({
						url: '/pages/pushactive/pushactive'
					});
				}
				if (index == 2) {
					this.showpush = false;
					// 发布动态
					uni.navigateTo({
						url: '/pages/pushdynamic/pushdynamic'
					});
				}
			},
			closepush(status) {
				this.showpush = status;
			},
			// 切换tab
			choosetab(index) {
				if (index != 5) {
					this.tabbarindex = index;
				}
				if (index == 1) {
					uni.redirectTo({
						url: '/pages/index/index'
					});
				}
				if (index == 2) {
					uni.redirectTo({
						url: '/dynamic/index/index'
					});
				}
				if (index == 3) {
					uni.redirectTo({
						url: '/message/index/index'
					});
				}
				if (index == 4) {
					uni.redirectTo({
						url: '/my/index/index'
					});
				}
				if (index == 5) {
					this.showpush = true;
				}
			}
		},
		onHide() {
			if (this.timer) {
				clearInterval(this.timer);
				this.timer = null;
			}
		},
		onUnload() {
			if (this.timer) {
				clearInterval(this.timer);
				this.timer = null;
			}
		}
	};
</script>

<style lang="scss" scoped>
	.container {
		font-size: 14px;
		line-height: 24px;
		background: linear-gradient(98deg, #fefbff 0%, #fffbf5 100%);

		.shenhe {
			box-sizing: border-box;
			width: 100%;
			height: 132rpx;
			background: #ffffef;
			border-radius: 0rpx 0rpx 0rpx 0rpx;
			display: flex;
			align-items: center;
			padding: 16rpx 30rpx;
		}

		.msglist {
			box-sizing: border-box;
			padding: 0 30rpx;

			.item {
				box-sizing: border-box;
				display: flex;
				padding: 30rpx 0;
				border-bottom: 2rpx solid #e8e8e8;
			}
		}
	}
</style>